package edu.spec.teacher.controller;

import edu.spec.basic.model.User;
import edu.spec.basic.model.dto.MvcReturn;
import edu.spec.basic.model.dto.UserDto;
import edu.spec.basic.model.enumeration.Status;
import edu.spec.basic.model.enumeration.YesNo;
import edu.spec.basic.service.iface.IUserService;
import edu.spec.teacher.model.Elect;
import edu.spec.teacher.service.iface.IElectService;
import org.madgecko.basic.model.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author       : MadFrog
 * Date         : 2018/10/6 16:23
 * Description  :
 */
@Controller
@RequestMapping("/teacher/")
public class ElectController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IElectService electService;

    /**
     * 创建选举主题
     * @param elect
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "elect/add", method = RequestMethod.POST)
    public Object add(Elect elect, HttpSession session){
        try {
            YesNo yesNo = elect.getAllowAbstain();
            if (yesNo==null){
                elect.setAllowAbstain(YesNo.NO);
            }
            List<Integer> candidateIds = new ArrayList<Integer>();
            String candidate = elect.getCandidate();
            if ("1".equals(candidate)){
                candidateIds = userService.listIdsByFormal(null);
            }else if("2".equals(candidate)){
                candidateIds = userService.listIdsByFormal(YesNo.YES);
            }else if("3".equals(candidate)){
                candidateIds = userService.listIdsByFormal(YesNo.NO);
            }else if("4".equals(candidate)){
                candidateIds = userService.listIdsByCommunist(YesNo.YES);
            }
            elect.setCandidate(idList2String(candidateIds));

            List<Integer> voterIds = new ArrayList<Integer>();
            String voter = elect.getVoter();
            if ("1".equals(voter)){
                voterIds = userService.listIdsByFormal(null);
            }else if("2".equals(voter)){
                voterIds = userService.listIdsByFormal(YesNo.YES);
            }else if("3".equals(voter)){
                voterIds = userService.listIdsByFormal(YesNo.NO);
            }else if("4".equals(voter)){
                voterIds = userService.listIdsByCommunist(YesNo.YES);
            }
            elect.setVoter(idList2String(voterIds));

            User u = (User)session.getAttribute("user");
            elect.setCreator(u);
            elect.setCreateDate(new Date());
            elect.setStatus(Status.ENABLED);
            elect.setCompleteNumber(0);
            elect.setCompleteRatio("0/" + voterIds.size());
            String fact = "";
            List<UserDto> userDtoList = userService.listUserDtoByIdString(elect.getCandidate());
            for(UserDto userDto : userDtoList){
                fact += userDto.getId() + ":" + userDto.getName() + ":0,";
            }
            fact = fact.substring(0, fact.length() - 1);
            elect.setFact(fact);
            electService.add(elect);
            return new MvcReturn(true, "创建投票成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new MvcReturn(false, "创建投票失败！原因：" + e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("elect/find")
    public Object find(){
        Pager<Elect> pagerElect = electService.find();
        return new MvcReturn(true, pagerElect.getDatas());
    }

    @ResponseBody
    @RequestMapping("elect/manage")
    public ModelAndView electManage(){
        Pager<Elect> pager = electService.find();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("electList", pager.getDatas());
        modelAndView.setViewName("teacher/electManage");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("electDetail/{id}")
    public ModelAndView electDetail(@PathVariable Integer id){
        Elect elect = electService.load(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("elect", elect);
        modelAndView.setViewName("teacher/electDetail");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("elect/toggleStatus/{id}")
    public MvcReturn toggleStatus(@PathVariable Integer id){
        Elect elect = electService.load(id);
        Status status = elect.getStatus();
        if (Status.ENABLED.equals(status)){
            elect.setStatus(Status.DISABLED);
        }else {
            elect.setStatus(Status.ENABLED);
        }
        electService.update(elect);
        return new MvcReturn(true, "成功切换状态为" + elect.getStatus().getName());
    }

    @ResponseBody
    @RequestMapping("elect/delete/{id}")
    public MvcReturn delete(@PathVariable Integer id){
        electService.delete(id);
        return new MvcReturn(true, "成功删除该投票");
    }

    /**
     * ID数组转字符串
     * @param ids
     * @return
     */
    private String idList2String(List<Integer> ids){
        String s = "";
        for (Integer i : ids){
            s += i + ",";
        }
        s = s.substring(0, s.length() - 1);
        return s;
    }

}
